using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Comteck.Dto.Orders;
using Comteck.Winforms.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace Comteck.Ktt.WinUI.Orders {
  /// <summary>
  /// 合并订单确认对话框
  /// </summary>
  public partial class FrmMergeOrdersDialog : FrmDialogBase {
    
    #region 字段
    
    private List<SaleOrderDto> _orderList;
    
    #endregion
    
    #region 构造函数
    
    /// <summary>
    /// 构造函数
    /// </summary>
    public FrmMergeOrdersDialog() {
      InitializeComponent();
    }
    
    #endregion
    
    #region 属性
    
    /// <summary>
    /// 可合并的订单列表
    /// </summary>
    public List<SaleOrderDto> OrderList {
      get { return _orderList; }
      set {
        _orderList = value;
        BindData();
      }
    }
    
    /// <summary>
    /// 选中要合并的订单ID列表
    /// </summary>
    public List<string> SelectedOrderIds { get; private set; }
    
    #endregion
    
    #region 方法
    
    /// <summary>
    /// 绑定数据
    /// </summary>
    private void BindData() {
      if (_orderList == null) return;
      
      // 按分组显示可合并的订单
      var groupedOrders = _orderList.GroupBy(o => new {
        RecipientAddress = o.RecipientAddress?.Trim(),
        RecipientMobile = o.RecipientPhone?.Trim(),
        SelfOrgName = o.SelfOrgName?.Trim()
      }).Where(g => g.Count() > 1).ToList();
      
      // 展开所有可合并的订单并添加分组信息
      var displayList = new List<MergeOrderDisplayDto>();
      foreach (var group in groupedOrders) {
        var groupKey = $"收件地址: {group.Key.RecipientAddress} | 手机号: {group.Key.RecipientMobile} | 自提点: {group.Key.SelfOrgName}";
        foreach (var order in group.OrderBy(o => o.Code)) {
          displayList.Add(new MergeOrderDisplayDto {
            Id = order.Id,
            Code = order.Code,
            GroupNumber = order.GroupNumber,
            BuyUserName = order.BuyUserName,
            RecipientName = order.Recipient,
            RecipientMobile = order.RecipientPhone,
            RecipientAddress = order.RecipientAddress,
            SelfOrgName = order.SelfOrgName,
            //GoodsQty = order.,
            //GoodsAmount = order.GoodsAmount,
            GoodsWeight = order.GoodsWeight,
            //GoodsNum = order.GoodsNum,
            //ImportTime = order.ImportTime,
            GroupKey = groupKey,
            Selected = true // 默认全选
          });
        }
      }
      
      gcMain.DataSource = displayList;
      
      // 更新统计信息
      UpdateStatistics();
    }
    
    /// <summary>
    /// 更新统计信息
    /// </summary>
    private void UpdateStatistics() {
      var selectedOrders = GetSelectedOrders();
      var totalOrders = selectedOrders.Count;
      var totalQty = selectedOrders.Sum(o => o.GoodsQty);
      var totalAmount = selectedOrders.Sum(o => o.GoodsAmount);
      var totalWeight = selectedOrders.Sum(o => o.GoodsWeight);
      
      lblStatistics.Text = $"共选中 {totalOrders} 个订单，总数量: {totalQty}，总金额: {totalAmount:F2}，总重量: {totalWeight:F2}";
    }
    
    /// <summary>
    /// 获取选中的订单
    /// </summary>
    /// <returns></returns>
    private List<MergeOrderDisplayDto> GetSelectedOrders() {
      var dataSource = gcMain.DataSource as List<MergeOrderDisplayDto>;
      return dataSource?.Where(o => o.Selected).ToList() ?? new List<MergeOrderDisplayDto>();
    }
    
    #endregion
    
    #region 事件处理
    
    /// <summary>
    /// 窗体加载事件
    /// </summary>
    private void FrmMergeOrdersDialog_Load(object sender, EventArgs e) {
      // 设置列宽
      colSelected.Width = 60;
      colCode.Width = 120;
      colGroupNumber.Width = 100;
      colBuyUserName.Width = 100;
      colRecipientName.Width = 100;
      colRecipientMobile.Width = 110;
      colRecipientAddress.Width = 200;
      colSelfOrgName.Width = 150;
      colGoodsQty.Width = 80;
      colGoodsAmount.Width = 80;
      colGoodsWeight.Width = 80;
      colGoodsNum.Width = 80;
      colImportTime.Width = 120;
      colGroupKey.Width = 300;
    }
    
    /// <summary>
    /// 全选/反选按钮点击事件
    /// </summary>
    private void btnSelectAll_Click(object sender, EventArgs e) {
      var dataSource = gcMain.DataSource as List<MergeOrderDisplayDto>;
      if (dataSource == null) return;
      
      var selectAll = dataSource.Any(o => !o.Selected);
      foreach (var order in dataSource) {
        order.Selected = selectAll;
      }
      
      gvMain.RefreshData();
      UpdateStatistics();
      btnSelectAll.Text = selectAll ? "反选" : "全选";
    }
    
    /// <summary>
    /// 确认合并按钮点击事件
    /// </summary>
    private void btnConfirm_Click(object sender, EventArgs e) {
      var selectedOrders = GetSelectedOrders();
      
      if (selectedOrders.Count < 2) {
        XtraMessageBox.Show("至少需要选择2个订单进行合并", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
      }
      
      // 验证选中的订单是否可以合并
      var groups = selectedOrders.GroupBy(o => o.GroupKey).ToList();
      var invalidGroups = groups.Where(g => g.Count() < 2).ToList();
      
      if (invalidGroups.Any()) {
        XtraMessageBox.Show("每个分组至少需要选择2个订单才能合并", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
      }
      
      var result = XtraMessageBox.Show(
        $"确定要合并选中的 {selectedOrders.Count} 个订单吗？\n\n合并后将保留每组的第一个订单，其他订单将被删除。",
        "确认合并",
        MessageBoxButtons.YesNo,
        MessageBoxIcon.Question);
        
      if (result == DialogResult.Yes) {
        SelectedOrderIds = selectedOrders.Select(o => o.Id).ToList();
        this.DialogResult = DialogResult.OK;
        this.Close();
      }
    }
    
    /// <summary>
    /// 取消按钮点击事件
    /// </summary>
    private void btnCancel_Click(object sender, EventArgs e) {
      this.DialogResult = DialogResult.Cancel;
      this.Close();
    }
    
    /// <summary>
    /// 复选框列变化事件
    /// </summary>
    private void gvMain_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) {
      if (e.Column.FieldName == "Selected") {
        UpdateStatistics();
        
        // 更新全选按钮状态
        var dataSource = gcMain.DataSource as List<MergeOrderDisplayDto>;
        if (dataSource != null) {
          btnSelectAll.Text = dataSource.All(o => o.Selected) ? "反选" : "全选";
        }
      }
    }
    
    #endregion
  }
  
  /// <summary>
  /// 合并订单显示DTO
  /// </summary>
  public class MergeOrderDisplayDto {
    public bool Selected { get; set; }
    public string Id { get; set; }
    public string Code { get; set; }
    public string GroupNumber { get; set; }
    public string BuyUserName { get; set; }
    public string RecipientName { get; set; }
    public string RecipientMobile { get; set; }
    public string RecipientAddress { get; set; }
    public string SelfOrgName { get; set; }
    public int GoodsQty { get; set; }
    public decimal GoodsAmount { get; set; }
    public decimal GoodsWeight { get; set; }
    public int GoodsNum { get; set; }
    public DateTime ImportTime { get; set; }
    public string GroupKey { get; set; }
  }
}